/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import Interfaces.ApparentModalI;
import Model.Playlist;
import Model.Playlistsong;
import java.awt.Frame;
import java.awt.Image;
import java.util.ArrayList;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.persistence.EntityManager;
import javax.persistence.RollbackException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import src.ApparentModalC;
import src.General;
import static src.General.dateFormater2;


/**
 *
 *
 */
public class MngPlaylist extends javax.swing.JFrame implements ApparentModalI{

    private Playlists prFrmPlaylists;
    private General.ActionType prEnmActionType;
    private EntityManager prEM;
    private String prUsername;
    private int prSelectedPlaylistRow;
    private Model.Playlist prSelectedPlaylist;
    private MngPlaylistAddSong prFrmMngPlaylistAddSong;
    private int selectedPlaylistSongRow;
    public ArrayList<Playlistsong> pbPlaylistSongsToBeDeletedList; 
    public ArrayList<Playlistsong> pbPlaylistSongsToBeAddedList;
    private MngPlaylistXML frmMngPlaylistXML;
    private JFrame next;
    /**
     * Creates new form MngPlaylist
     */
    public MngPlaylist(Playlists frmPlaylists, Playlist selectedPlaylist, General.ActionType enmActionType, EntityManager em, String username, int selectedRow) 
    {
        try 
        {
            this.prFrmPlaylists = frmPlaylists;
            this.prEM = em;
            this.prEnmActionType = enmActionType;
            this.prUsername = username;
            this.prSelectedPlaylistRow = selectedRow;
            
            this.prSelectedPlaylist = selectedPlaylist;
            this.pbPlaylistSongsToBeDeletedList = new ArrayList<Playlistsong>();
            this.pbPlaylistSongsToBeAddedList = new ArrayList<Playlistsong>();
            
            initComponents();
            
            General.disableDeleteUpdateIf(this.songsTable, this.btnRemoveSong, null);

            Image applicationImage = ImageIO.read(getClass().getResource("/Images/note1.png"));
            this.setIconImage(applicationImage);
            
            switch(prEnmActionType)
            {
                case Insert:
                    this.setTitle(this.getTitle() + " - " + "Δημιουργία");
                    this.btnSave.setText("Δημιουργία");
                    txtDateOfCreation.setText(dateFormater2.format(new Date()));
                    txtDateOfCreation.setEnabled(false);
                    btnExportXML.setEnabled(false);
                    break;
                case Update:
                    this.setTitle(this.getTitle() + " - " + "Τροποποίηση");
                    this.btnSave.setText("Τροποποίηση");
                    txtPlaylistName.setText(this.prSelectedPlaylist.getPlaylistName());
                    txtDescription.setText(this.prSelectedPlaylist.getDescription());
                    txtDateOfCreation.setText(dateFormater2.format(this.prSelectedPlaylist.getCreatedDate()));
                    txtDateOfCreation.setEnabled(false);
                    break;   
                case Delete:
                    this.setTitle(this.getTitle()+" - " + "Διαγραφή");
                    this.btnSave.setText("Διαγραφή");
                    txtPlaylistName.setText(this.prSelectedPlaylist.getPlaylistName());
                    txtDescription.setText(this.prSelectedPlaylist.getDescription());
                    txtDateOfCreation.setText(dateFormater2.format(this.prSelectedPlaylist.getCreatedDate()));
                    General.disableFieldsNCombos(this.playlistInfoPanel);
                    txtDescription.setEnabled(false);
                    btnAddSong.setEnabled(false);
                    btnRemoveSong.setEnabled(false);
                    songsTable.setEnabled(false);
                    btnImportXML.setEnabled(false);
                    break;
                default:
                    break;
            }            

        } 
        catch (Exception ex) 
        {
            JOptionPane.showMessageDialog(this, ex.getMessage(), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
    }



    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        playlistSongsQuery = prEM.createQuery("SELECT ps FROM Playlistsong ps WHERE ps.playlistId = :selectedPlaylist ORDER BY ps.orderNum").setParameter("selectedPlaylist", prSelectedPlaylist);
        playlistSongsList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(playlistSongsQuery.getResultList());
        btnCancel = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        btnSave = new javax.swing.JButton();
        playlistInfoPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtDescription = new javax.swing.JTextArea();
        txtPlaylistName = new javax.swing.JTextField();
        txtDateOfCreation = new javax.swing.JTextField();
        lblPlaylistName = new javax.swing.JLabel();
        lblDescription = new javax.swing.JLabel();
        lblDateOfCreation = new javax.swing.JLabel();
        playlistSongsPanel = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        songsTable = new javax.swing.JTable();
        btnRemoveSong = new javax.swing.JButton();
        btnAddSong = new javax.swing.JButton();
        lblXML = new javax.swing.JLabel();
        btnExportXML = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JSeparator();
        btnImportXML = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Radio Station - Φόρμα Διαχείρισης Λίστας");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        btnCancel.setText("Ακύρωση");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        btnSave.setText("Αποθήκευση");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        playlistInfoPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Στοιχεία Λίστας"));

        txtDescription.setColumns(20);
        txtDescription.setRows(5);
        jScrollPane1.setViewportView(txtDescription);

        txtDateOfCreation.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtDateOfCreationActionPerformed(evt);
            }
        });

        lblPlaylistName.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblPlaylistName.setForeground(new java.awt.Color(204, 0, 0));
        lblPlaylistName.setText("Όνομα Λίστας");

        lblDescription.setText("Περιγραφή");

        lblDateOfCreation.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblDateOfCreation.setForeground(new java.awt.Color(204, 0, 0));
        lblDateOfCreation.setText("Ημερομηνία Δημιουργίας");

        javax.swing.GroupLayout playlistInfoPanelLayout = new javax.swing.GroupLayout(playlistInfoPanel);
        playlistInfoPanel.setLayout(playlistInfoPanelLayout);
        playlistInfoPanelLayout.setHorizontalGroup(
            playlistInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, playlistInfoPanelLayout.createSequentialGroup()
                .addGroup(playlistInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblPlaylistName)
                    .addComponent(lblDescription)
                    .addComponent(lblDateOfCreation))
                .addGap(14, 14, 14)
                .addGroup(playlistInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtPlaylistName, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1)
                    .addComponent(txtDateOfCreation))
                .addContainerGap())
        );
        playlistInfoPanelLayout.setVerticalGroup(
            playlistInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(playlistInfoPanelLayout.createSequentialGroup()
                .addGroup(playlistInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPlaylistName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblPlaylistName))
                .addGroup(playlistInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(playlistInfoPanelLayout.createSequentialGroup()
                        .addGap(7, 7, 7)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(playlistInfoPanelLayout.createSequentialGroup()
                        .addGap(31, 31, 31)
                        .addComponent(lblDescription)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(playlistInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtDateOfCreation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblDateOfCreation))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        playlistSongsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Τραγούδια Λίστας"));

        songsTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, playlistSongsList, songsTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${songId.songTitle}"));
        columnBinding.setColumnName("Τίτλος");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${songId.albumId.artistId}"));
        columnBinding.setColumnName("Καλλιτέχνης");
        columnBinding.setColumnClass(Model.Artist.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${songId.albumId.musicGroupId.musicGroupName}"));
        columnBinding.setColumnName("Συγκρότημα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${songId.duration}"));
        columnBinding.setColumnName("Διάρκεια (sec)");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${orderNum}"));
        columnBinding.setColumnName("Σειρά");
        columnBinding.setColumnClass(Integer.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane2.setViewportView(songsTable);

        btnRemoveSong.setText("Διαγραφή Τραγουδιού");
        btnRemoveSong.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveSongActionPerformed(evt);
            }
        });

        btnAddSong.setText("Εισαγωγή Τραγουδιού");
        btnAddSong.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddSongActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout playlistSongsPanelLayout = new javax.swing.GroupLayout(playlistSongsPanel);
        playlistSongsPanel.setLayout(playlistSongsPanelLayout);
        playlistSongsPanelLayout.setHorizontalGroup(
            playlistSongsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(playlistSongsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(playlistSongsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 772, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, playlistSongsPanelLayout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnAddSong)
                        .addGap(128, 128, 128)
                        .addComponent(btnRemoveSong)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        playlistSongsPanelLayout.setVerticalGroup(
            playlistSongsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(playlistSongsPanelLayout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 207, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(playlistSongsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAddSong)
                    .addComponent(btnRemoveSong)))
        );

        lblXML.setText("Διαχείριση Λίστας μέσω XML αρχείου");

        btnExportXML.setText("Εξαγωγή Λίστας σε XML");
        btnExportXML.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExportXMLActionPerformed(evt);
            }
        });

        btnImportXML.setText("Εισαγωγή Λίστας από αρχείο XML");
        btnImportXML.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImportXMLActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(playlistSongsPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnCancel))
                    .addComponent(playlistInfoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jSeparator2)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblXML)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnExportXML)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnImportXML)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(playlistInfoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(playlistSongsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblXML)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnExportXML)
                    .addComponent(btnImportXML))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 3, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancel)
                    .addComponent(btnSave))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    
    public void HandleButtons()
    {
        try 
        {
            General.enableDeleteUpdateIf(this.songsTable, this.btnRemoveSong, null);
            General.disableDeleteUpdateIf(this.songsTable, this.btnRemoveSong, null);
        } 
        catch (Exception ex) 
        {
            // Do nothing, swallow error
        }

    }    
    
    
    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        try 
        {
            //this.prFrmPlaylists.setEnabled(true);   
            this.prEM.clear();
            this.prFrmPlaylists.playlistList.clear();
            this.prFrmPlaylists.playlistList.addAll(this.prFrmPlaylists.playlistQuery.getResultList());
            General.closeWindowX(this);
        } 
        catch (Exception ex) 
        {
            JOptionPane.showMessageDialog(this, ex.getMessage(), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnCancelActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        try
        {
            String[] options = {"NAI","OXI"};
            int optionResult;
            int songsDuration = 0;
            int minSongsDuration = 30*60;   
            
            this.txtPlaylistName.setText(this.txtPlaylistName.getText().trim());
            this.txtDescription.setText(this.txtDescription.getText().trim());
            
            General.CheckTextfield(this.txtPlaylistName.getText(), this.lblPlaylistName.getText(), true, true, 50, true);
            
            
            switch(prEnmActionType)
            {
                case Insert:                 
                    for (Playlistsong objPlaylistsong : playlistSongsList) 
                    {
                        songsDuration = songsDuration + objPlaylistsong.getSongId().getDuration();
                    }

                    if (songsDuration < minSongsDuration)
                    {
                        throw new Exception("Η συγκεκριμένη λίστα περιέχει τραγούδια συνολικής διάρκειας '" + songsDuration + " seconds' ενώ η ελάχιστη επιτρεπτή διάρκεια είναι '" + minSongsDuration + " seconds'.\r\n\r\nΠαρακαλώ προσθέστε και άλλα τραγούδια!");
                    }                    
                    
                    this.prSelectedPlaylist.setPlaylistName(txtPlaylistName.getText());
                    this.prSelectedPlaylist.setDescription(txtDescription.getText());
                    this.prSelectedPlaylist.setCreatedBy(this.prUsername);
                    this.prSelectedPlaylist.setCreatedDate(new Date());

                    try
                    {
                        this.prEM.getTransaction().begin();
                        this.prEM.persist(this.prSelectedPlaylist);

                        for (Playlistsong objPlaylistsong : pbPlaylistSongsToBeAddedList) 
                        {
                            objPlaylistsong.setCreatedDate(new Date());
                            this.prEM.persist(objPlaylistsong);
                        }
                        for (Playlistsong objSong : pbPlaylistSongsToBeDeletedList) 
                        {
                            this.prEM.remove(objSong);
                        }                        
                                                
                        // Αποθήκευση στη βάση
                        this.prEM.getTransaction().commit();

                        JOptionPane.showMessageDialog(this, "Η δημιουργία ολοκληρώθηκε επιτυχώς!", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
                        
                        this.prFrmPlaylists.playlistList.add(this.prSelectedPlaylist);
                        this.prFrmPlaylists.HandleButtons();
                        
                        
                        this.prSelectedPlaylist = new Playlist();
                        txtPlaylistName.setText("");
                        txtDescription.setText("");
                        this.pbPlaylistSongsToBeDeletedList.clear();
                        this.pbPlaylistSongsToBeAddedList.clear();
                        this.playlistSongsList.clear();
                        HandleButtons();
                    }
                    catch (RollbackException rbe)
                    {            
                        if(this.prEM.getTransaction().isActive())
                        {
                            this.prEM.getTransaction().rollback();
                        }
                        if(rbe.getMessage().contains("UI_PLAYLIST2"))
                        {
                            JOptionPane.showMessageDialog(this, "Η δημιουργία δεν ολοκληρώθηκε!\r\n\r\nΗ συγκεκριμένη λίστα υπάρχει ήδη!", this.getTitle(), JOptionPane.ERROR_MESSAGE);
                        }
                        else
                        {
                            JOptionPane.showMessageDialog(this, "Η δημιουργία δεν ολοκληρώθηκε!\r\n\r\n" + rbe.getMessage(), this.getTitle(), JOptionPane.ERROR_MESSAGE);
                        }
                        
                    }
                    catch (Exception e)
                    {            
                        if(this.prEM.getTransaction().isActive())
                        {
                            this.prEM.getTransaction().rollback();
                        }
                                                
                        JOptionPane.showMessageDialog(this, "Η δημιουργία δεν ολοκληρώθηκε!\r\n\r\n" + e.getMessage(), this.getTitle(), JOptionPane.ERROR_MESSAGE);
                    }

                    
                    this.pbPlaylistSongsToBeDeletedList.clear();
                    this.pbPlaylistSongsToBeAddedList.clear();
                    this.playlistSongsList.clear();
                    HandleButtons();

                    btnCancel.setText("Έξοδος");

                    break;
                case Update:

                    optionResult = JOptionPane.showOptionDialog(null, "Είστε σίγουροι ότι θέλετε να τροποποιήσετε την συγκεκριμένη λίστα;",
                                                              this.getTitle(), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); 
                    if (optionResult == JOptionPane.YES_OPTION)
                    {
                        for (Playlistsong objPlaylistsong : playlistSongsList) 
                        {
                            songsDuration = songsDuration + objPlaylistsong.getSongId().getDuration();
                        }

                        if (songsDuration < minSongsDuration)
                        {
                            throw new Exception("Η συγκεκριμένη λίστα περιέχει τραγούδια συνολικής διάρκειας '" + songsDuration + " seconds' ενώ η ελάχιστη επιτρεπτή διάρκεια είναι '" + minSongsDuration + " seconds'.\r\n\r\nΠαρακαλώ προσθέστε και άλλα τραγούδια!");
                        }           
                        this.prSelectedPlaylist.setPlaylistName(txtPlaylistName.getText());
                        this.prSelectedPlaylist.setDescription(txtDescription.getText());
                        this.prSelectedPlaylist.setModifiedBy(this.prUsername);
                        this.prSelectedPlaylist.setModifiedDate(new Date());

                        try
                        {
                            this.prEM.getTransaction().begin();
                            this.prEM.persist(this.prSelectedPlaylist);

                            for (Playlistsong objSong : pbPlaylistSongsToBeDeletedList) 
                            {
                                this.prEM.remove(objSong);
                            }
                            for (Playlistsong objPlaylistsong : pbPlaylistSongsToBeAddedList) 
                            {
                                objPlaylistsong.setCreatedDate(new Date());
                                this.prEM.persist(objPlaylistsong);
                            }
                            
                            for (Playlistsong objSong : playlistSongsList) 
                            {
                                if (!objSong.getCreatedBy().isEmpty())
                                {
                                    objSong.setModifiedBy(this.prUsername);
                                    objSong.setModifiedDate(new Date());
                                }
                                
                            }

                            // Αποθήκευση στη βάση
                            this.prEM.getTransaction().commit();

                            JOptionPane.showMessageDialog(this, "Η τροποποίηση ολοκληρώθηκε επιτυχώς!", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
                            
                            this.prFrmPlaylists.playlistList.set(this.prSelectedPlaylistRow, this.prSelectedPlaylist);
                        }
                        catch (RollbackException rbe)
                        {            
                            
                            if(this.prEM.getTransaction().isActive())
                            {
                                this.prEM.getTransaction().rollback();
                            }

                            if(!this.prEM.contains(this.prSelectedPlaylist))
                            {
                                //After the RollbackException the 'prSelectedPlaylist' is no longer managed by the 'prEM'!!!
                                //Until finding a solution to this problem, the user is forced to exit the form 
                                //in order to do his modifications from the beginning

                                if(rbe.getMessage().contains("UI_PLAYLIST2"))
                                {
                                    JOptionPane.showMessageDialog(this, "Η τροποποίηση δεν ολοκληρώθηκε!\r\n\r\nΗ συγκεκριμένη λίστα υπάρχει ήδη!\r\n\r\nΠαρακαλώ προσπαθήστε ξανά!", this.getTitle(), JOptionPane.ERROR_MESSAGE);
                                }
                                else
                                {
                                    JOptionPane.showMessageDialog(this, "Η τροποποίηση δεν ολοκληρώθηκε!\r\n\r\nΠαρακαλώ προσπαθήστε ξανά!\r\n\r\n" + rbe.getMessage(), this.getTitle(), JOptionPane.ERROR_MESSAGE);
                                }                                  
                                
                                
                                //this.prFrmPlaylists.setEnabled(true);   
                                this.prEM.clear();
                                this.prFrmPlaylists.playlistList.clear();
                                this.prFrmPlaylists.playlistList.addAll(this.prFrmPlaylists.playlistQuery.getResultList());
                                General.closeWindowX(this);                               
                                
                                
                            }
                            else
                            {

                                this.prEM.clear();
                                if(rbe.getMessage().contains("UI_PLAYLIST2"))
                                {
                                    JOptionPane.showMessageDialog(this, "Η τροποποίηση δεν ολοκληρώθηκε!\r\n\r\nΗ συγκεκριμένη λίστα υπάρχει ήδη!\r\n\r\n" + rbe.getMessage(), this.getTitle(), JOptionPane.ERROR_MESSAGE);
                                }
                                else
                                {
                                    JOptionPane.showMessageDialog(this, "Η τροποποίηση δεν ολοκληρώθηκε!\r\n\r\n" + rbe.getMessage(), this.getTitle(), JOptionPane.ERROR_MESSAGE);
                                }                            
                            }

                        }
                        catch (Exception e)
                        {            
                            if(this.prEM.getTransaction().isActive())
                            {
                                this.prEM.getTransaction().rollback();
                            }
                                                        
                            JOptionPane.showMessageDialog(this, "Η τροποποίηση δεν ολοκληρώθηκε!\r\n\r\n" + e.getMessage(), this.getTitle(), JOptionPane.ERROR_MESSAGE);
                        }

                        btnCancel.setText("Έξοδος");

                    }
                    break;   
                case Delete:

                    optionResult = JOptionPane.showOptionDialog(null, "Είστε σίγουροι ότι θέλετε να σβήσετε την συγκεκριμένη λίστα;",
                                                              this.getTitle(), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); 
                    if (optionResult == JOptionPane.YES_OPTION)
                    {

                        try
                        {
                            this.prEM.getTransaction().begin();                                                          
                            this.prEM.remove(this.prSelectedPlaylist);
                            
                            for (Playlistsong objSong : playlistSongsList) 
                            {
                                this.prEM.remove(objSong);
                            }
                            
                            // Αποθήκευση στη βάση
                            this.prEM.getTransaction().commit();

                            JOptionPane.showMessageDialog(this, "Η διαγραφή ολοκληρώθηκε επιτυχώς!", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
                            
                            this.prFrmPlaylists.playlistList.remove(this.prSelectedPlaylist);
                            this.prFrmPlaylists.HandleButtons();
                            this.btnExportXML.setEnabled(false);
                            
                        }
                        catch (Exception e)
                        {            
                            if(this.prEM.getTransaction().isActive())
                            {
                                this.prEM.getTransaction().rollback();
                            }
                            JOptionPane.showMessageDialog(this, "Η διαγραφή δεν ολοκληρώθηκε!\r\n\r\n" + e.getMessage(), this.getTitle(), JOptionPane.ERROR_MESSAGE);
                        }

                        btnSave.setEnabled(false);
                        btnCancel.setText("Έξοδος");
                    }
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            JOptionPane.showMessageDialog(this, ex.getMessage(), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }

    }//GEN-LAST:event_btnSaveActionPerformed

    private void txtDateOfCreationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtDateOfCreationActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtDateOfCreationActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        
        try
        {
            //this.prFrmPlaylists.setEnabled(true);
            this.prEM.clear();
            this.prFrmPlaylists.playlistList.clear();
            this.prFrmPlaylists.playlistList.addAll(this.prFrmPlaylists.playlistQuery.getResultList());
        }
        catch (Exception ex)
        {
            JOptionPane.showMessageDialog(this, ex.getMessage(), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_formWindowClosing

    private void btnExportXMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExportXMLActionPerformed
        try 
        {
            frmMngPlaylistXML = new MngPlaylistXML(null, this, prSelectedPlaylist, General.XMLActionType.Export, this.prEM, this.prUsername);
            //frmMngPlaylistXML.setVisible(true);
            //this.setEnabled(false);
            ApparentModalC.modalSetNextVisible(this, frmMngPlaylistXML);
        } 
        catch (Exception ex) 
        {
            JOptionPane.showMessageDialog(this, ex.getMessage(), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnExportXMLActionPerformed

    private void btnImportXMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImportXMLActionPerformed
        try 
        {
            frmMngPlaylistXML = new MngPlaylistXML(null, this, prSelectedPlaylist, General.XMLActionType.Import, this.prEM, this.prUsername);
            //frmMngPlaylistXML.setVisible(true);
            //this.setEnabled(false);
            ApparentModalC.modalSetNextVisible(this, frmMngPlaylistXML);
        } 
        catch (Exception ex) 
        {
            JOptionPane.showMessageDialog(this, ex.getMessage(), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnImportXMLActionPerformed

    private void btnAddSongActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddSongActionPerformed

        try
        {
            prFrmMngPlaylistAddSong = new MngPlaylistAddSong(this, this.prSelectedPlaylist, this.prEM, this.prUsername);
            //prFrmMngPlaylistAddSong.setVisible(true);
           // this.setEnabled(false);
            ApparentModalC.modalSetNextVisible(this, prFrmMngPlaylistAddSong);

        }
        catch (Exception ex)
        {
            JOptionPane.showMessageDialog(this, ex.getMessage(), this.getTitle(), 0);
        }
    }//GEN-LAST:event_btnAddSongActionPerformed

    private void btnRemoveSongActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveSongActionPerformed

        try
        {
            Playlistsong selectedPlaylistSong;
            this.selectedPlaylistSongRow = this.songsTable.getSelectedRow();

            if(this.selectedPlaylistSongRow == -1)
            {
                JOptionPane.showMessageDialog(this, "Παρακαλώ επιλέξτε πρώτα το τραγούδι που επιθυμείτε να διαγράψετε!", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
            }
            else
            {
                selectedPlaylistSong = playlistSongsList.get(songsTable.convertRowIndexToModel(this.selectedPlaylistSongRow));

                if (pbPlaylistSongsToBeAddedList.contains(selectedPlaylistSong))
                {
                    pbPlaylistSongsToBeAddedList.remove(selectedPlaylistSong);
                }
                else
                {
                    this.pbPlaylistSongsToBeDeletedList.add(selectedPlaylistSong);
                }

                this.playlistSongsList.remove(selectedPlaylistSong);
                HandleButtons();
            }
        }
        catch (Exception ex)
        {
            JOptionPane.showMessageDialog(this, ex.getMessage(), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }

    }//GEN-LAST:event_btnRemoveSongActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddSong;
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnExportXML;
    private javax.swing.JButton btnImportXML;
    private javax.swing.JButton btnRemoveSong;
    private javax.swing.JButton btnSave;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JLabel lblDateOfCreation;
    private javax.swing.JLabel lblDescription;
    private javax.swing.JLabel lblPlaylistName;
    private javax.swing.JLabel lblXML;
    private javax.swing.JPanel playlistInfoPanel;
    public java.util.List<Model.Playlistsong> playlistSongsList;
    private javax.swing.JPanel playlistSongsPanel;
    private javax.persistence.Query playlistSongsQuery;
    private javax.swing.JTable songsTable;
    private javax.swing.JTextField txtDateOfCreation;
    private javax.swing.JTextArea txtDescription;
    private javax.swing.JTextField txtPlaylistName;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    @Override
    public Frame getCaller() {
        return this.prFrmPlaylists;
    }

    @Override
    public Frame getNext() {
        return this.next;
    }

    @Override
    public void setCallersNextNull() {
        ((ApparentModalI) this.prFrmPlaylists).setNext(null);
    }

    @Override
    public void setNext(Frame w) {
        this.next = (JFrame) w;
    }
}
